package com.maxd.service.selfCoupon;

import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.SelfCoupon;
import com.maxd.respository.selfCoupon.SelfCouponIssueJpaRepository;
import com.maxd.respository.selfCoupon.SelfCouponJpaRepository;
import com.maxd.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class SelfCouponServiceImpl implements SelfCouponService {
    @Autowired
    private SelfCouponJpaRepository jpaRepository;
    @Autowired
    private SelfCouponIssueJpaRepository selfCouponIssueJpaRepository;

    @Override
    public Result findAll(Integer page, Integer size, Long storeId) {
        Pageable pageable = PageRequest.of(page, size, Sort.by(new Sort.Order(Sort.Direction.DESC, "sort")));
        Specification<SelfCoupon> queryCondition = new Specification<SelfCoupon>() {
            @Override
            public Predicate toPredicate(Root<SelfCoupon> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (storeId != null) {
                    predicateList.add(criteriaBuilder.equal(root.get("storeId"), storeId));
                }else {
                    predicateList.add(criteriaBuilder.isNull(root.get("storeId")));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return ResultUtil.success(jpaRepository.findAll(queryCondition, pageable));
    }


    @Override
    public Result saveBody(SelfCoupon entity) {
        entity.setCreateTime(DateUtil.createTime());
        return ResultUtil.success(jpaRepository.save(entity));
    }

    @Override
    public Result updateBody(SelfCoupon entity) {
        SelfCoupon save = jpaRepository.save(entity);
        selfCouponIssueJpaRepository.updateSelfCouponIssue(save.getCouponName(),save.getGoodsImages(),save.getLessMoney(),save.getMinMoney(),save.getCouponId());
        return ResultUtil.success();
    }

    @Override
    public Result findOne(Long id) {
        return ResultUtil.success(jpaRepository.findById(id).orElse(null));
    }

    @Override
    public Result delete(Long id) {
        jpaRepository.deleteById(id);
        return ResultUtil.success();
    }
}
